package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据toUserId查询推荐用户
     *   今日佳人：查询和toUserId相似度最高的一个推荐数据
     *   SQL：select * from table where toUserId = 1
     */
    public RecommendUser queryWitchMaxScore(Long toUserId) {
        //1、创建Criteria对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、创建Query对象
        Query query = Query.query(criteria)
                           .with(Sort.by(Sort.Order.desc("score"))) //排序
                           .limit(1);  //每页查询1条，查询第一页
        //3、调用mongoTemplate查询（findOne）
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    //根据toUserId分页查询推荐用户
    public List<RecommendUser> queryRecommendUserList(Long toUserId, Integer page, Integer pagesize) {
        //1、创建Criteria对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、创建Query对象
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, RecommendUser.class);
        System.out.println("总数="+count);
        //4、向Query对象中设置分页参数
        query.with(Sort.by(Sort.Order.desc("score")))
             .skip((page-1) * pagesize)
             .limit(pagesize);
        //5、查询当前页的数据列表
        return mongoTemplate.find(query,RecommendUser.class);
    }

    //根据userId和toUserId查询推荐信息
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("toUserId").is(toUserId);
        Query query = Query.query(criteria);
        return mongoTemplate.findOne(query,RecommendUser.class);
    }
}
